define(function(require) {
    //去掉IE input大小写提示
    document.msCapsLockWarningOff = true;
    
    
    var $ = require('jquery'),
        tool = require('tools'),
        colorbox = require('jquery.colorbox');
    if(window.addEventListener){
        var _height = document.body.clientHeight;
    }else{
        var _height = document.documentElement.clientHeight;
    }
    
    if(_height > 575 && _height < 620 ){
        $('body').addClass('s-screen');
    }else if(_height < 572) {
        $('body').addClass('ss-screen');
    }
    
    var mousedownHappened = false;
    $('a').mousedown(function() {
        mousedownHappened = true;
    });
    
    var Validate = function(){}

    Validate.prototype = {

        init: function() {
            this.$input = $('input[data-rule]');
            this.$areaLi=$(".area-list");
            this.$telCountryNo = $('#tel_country_no');
            this.$submit = $('input[type="submit"]');


            this.bind();
        },

        bind: function() {
            var self = this;

            this.$areaLi.on('click',function(){
                    console.log('click');
        	});

            this.$input
                .off().on('focus', function() {
                    var el = $(this);

                    if(el.next('p').length){
                        el.parents('li').removeClass('error');
                        el.next('p').remove();
                    }
                })
                .off('blur').on('blur', function(e){
                    if(mousedownHappened) // cancel the blur event
                    {
                        $(this).focus();
                        mousedownHappened = false;
                    }else{
                        var el = $(this),
                        val = $.trim( el.val() ),
                        ruleStr = el.data('rule'),
                        name = el.data('name');

                        self.loopRule(el, val, ruleStr, name);
                    }
                   

                })
        },

        // 循环验证规则
        loopRule: function(el, val, ruleStr, name) {
            var ruleArr = ruleStr.split('|');
            var self = this;
            for(var i = 0,len = ruleArr.length; i < len; i++){
                if(typeof self.$telCountryNo != "undefined" && self.$telCountryNo.text() != '+86' && ruleArr[i] === 'phone'){
                	continue;
                }else{
                    if( !this.verify(el, val, ruleArr[i], name) ){
                        break;
                    }                	
                }
            }
        },

        

        // 处理验证函数
        verify: function(el, val, rule, name) {
            switch(rule){
                case 'empty':

                    if( tool.validateRules.isEmpty(val) ){
                        this.showErr(el, tool.error_tpl.common_empty, name);
                        return false;
                    }else{
                        return true;
                    }
                    break;

                case 'phone':
                    if( !tool.validateRules.isMobile(val) ){
                        this.showErr(el, tool.error_tpl.phone_error);
                        return false;
                    }else{
                       return true; 
                    }
                    break;

                case 'msgcode':
                    if( !tool.validateRules.isMsgCode(val) ){
                        this.showErr(el, tool.error_tpl.msgcode_error);
                        return false;
                    }
                    break;
                case 'emailcode':
                    if( !tool.validateRules.isAuthCode(val) ){
                        this.showErr(el, tool.error_tpl.emailcode_error);
                        return false;
                    }
                    break;

                case 'authcode':
                    if( !tool.validateRules.isAuthCode(val) ){
                        this.showErr(el, tool.error_tpl.authcode_error);
                        return false;
                    }
                    break;

                case 'password':
                    if( !tool.validateRules.betweenLength(val, 8, 20) ){
                        this.showErr(el, tool.error_tpl.password_length);
                        return false;
                    }else if( tool.validateRules.isIllegalPwd(val) ){
                        this.showErr(el, tool.error_tpl.password_format);
                        return false;
                    }else if( tool.validateRules.isNumber(val) ){
                        this.showErr(el, tool.error_tpl.password_number_format);
                        return false;
                    }else if( tool.validateRules.isLetter(val) ){
                        this.showErr(el, tool.error_tpl.password_letter_format);
                        return false;
                    }else if( tool.validateRules.isSign(val) ){
                        this.showErr(el, tool.error_tpl.password_sign_format);
                        return false;
                    }else if( tool.validateRules.isAllSame(val) ){
                        this.showErr(el, tool.error_tpl.password_allsame);
                        return false;
                    }else{
                        return true;
                    }
                    break;

                case 'same':
                    var prev = $(el).parents('li').prev('li').find('input[type="password"]').val(),
                        confirm = $(el).val();


                    if( !tool.validateRules.isStrRepeat(prev, confirm) ){
                        this.showErr(el, tool.error_tpl.password_repeat);
                        return false;
                    }else{
                        this.hideErr(el);
                        return true;
                    }

                case 'mail':
                    if( !tool.validateRules.isEmail(val) ){
                        this.showErr(el, tool.error_tpl.email_format);
                        return false;
                    }else{
                        return true;
                    }

                default:
                    break; 
            }
        },

        // 显示错误信息,传入name控制提示的主语
        showErr: function(el, tips, name) {

            var errorInfo = typeof name == 'undefined' ? tips : ('请输入' + name) ;

            if($(el).siblings('.error-tips').length == 0){
                $(el)
                    .parents('li').addClass('error').end()
                    .after('<p class="error-tips">'+errorInfo+'</p>')
            }else{


                $(el).siblings('.error-tips').remove();
                $(el)
                    .parents('li').addClass('error').end()
                    .after('<p class="error-tips">'+errorInfo+'</p>')
                return;
            }

            if(this.$submit.hasClass('btn-disable')){
                this.$submit.removeClass("btn-disable").removeAttr("disabled");
            }
            
        },

        hideErr: function(el) {
            if(el.next('p').length){
                el.parents('li').removeClass('error');
                el.next('p').remove();
            }

        }

    };

    $.fn.popError = function(tips, callback, time) {
       
        var $wrap = $('.login-wrap'),
            $pop = $('<div class="popError"></div>'),
            innerHTML = $(this).data('inner'),
            time = time*1000 || 1200,
            self = $(this);

        $pop.html(tips);
        $wrap.append($pop);

        
    

        setTimeout(function() {
            $pop.remove();

            self.removeClass("btn-disable").removeAttr("disabled");
            
            callback && callback();
        }, time);  
    }

    /**
     *  倒计时函数
     */

    var countDown = {
        init: function(){
            this.verBtn = $(".get-vercode:visible");
            this.info = this.verBtn.data('btn');
            this.reset();
        },
        start: function(callback){
            this.timer2 = null;
            this.countdownTime = 60;
            this.callback = callback;
            
            var that = this;
            
            this.verBtn.addClass("btn-disable").attr("disabled", "disabled").html(this.info);
            
            this.timer2 = setInterval(function() {
                that.countdownTime--;
                if (that.countdownTime >= 0) {
                    that.verBtn.html(that.countdownTime + "秒后重发")
                } else {
                    clearInterval(that.timer2);
                    that.callback && that.callback();
                    return;
                }
            }, 1000);
        },
        reset: function() {
           clearInterval(this.timer2);
           var _info = this.info != undefined ? this.info : '';
           var _html = ~_info.indexOf('短信') ? '获取短信验证码' : '发送验证码到邮箱';
           
           this.verBtn.removeClass("btn-disable").removeAttr("disabled").html(_html);
           
        }
    };
    countDown.init();


    $.fn.cssEnd = function ( callback ){
        var EventAnimateEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
        this.one(EventAnimateEnd , callback);
        return this;
    }


    /**
     *  切换校验码
     */

    var authcode = {
        // 插入验证码或极验证
        // flag参数 传值则动态生成后自动聚焦 
        show: function(flag) {
            var valiStr =  '<li class="clearfix" id="J_valiIpt">\
                                <div class="ipt-wrap valicode-wrap fl">\
                                    <input type="text" placeholder="输入右侧验证码" name="verifyCode" tabindex="3" class="authcode fl" id="J_authcode" maxlength="6" data-rule="empty|authcode" data-name="验证码">\
                                </div>\
                                <img src="/pc/verifyimg" alt="" class="vali-img fl" id="j_img">\
                                <a href="javascript:;" class="refresh-btn fr" id="J_refresh"></a>\
                            </li>';

            $('#J_insertVali').after(valiStr);
            this.init(flag);
        },
        init: function(flag) {
            this.$refresh = $('.refresh-btn:visible');
            this.$valiImg = $('.vali-img:visible');
            this.$valiCode = $('.authcode:visible');
            if(flag){
                this.$valiCode.focus();
            }

            this.imgSrc = this.$valiImg.attr('src');

            this.bind();
        },

        bind: function() {
            var self = this;
            this.$refresh
                .on('click', function(e) {
                    e.preventDefault();
                    var $this = $(this);
                    // 区分IE9及以下浏览器
                    if (supportCss3('text-shadow')) {
                        if($this.hasClass('refreshing')){
                            return;
                        }
                        $this.addClass('refreshing');
                        $this.cssEnd(function() {
                            self.$valiImg.attr('src', self.imgSrc +'?'+ new Date().getTime());
                            $this.removeClass('refreshing');
                        })
                    } else {
                        self.$valiImg.attr('src', self.imgSrc +'?'+ new Date().getTime());

                    }
                })

            this.$valiImg
                .on('click', function() {
                    self.$refresh.trigger('click');
                })

            new Validate().init();
        }

    };

    /**
     *  判断是否支持css3
     */
    
    function supportCss3(style) { 
        var prefix = ['webkit', 'Moz', 'ms', 'o'], 
            i, 
            humpString = [], 
            htmlStyle = document.documentElement.style, 
            _toHumb = function (string) { 
                return string.replace(/-(\w)/g, function ($0, $1) { 
                    return $1.toUpperCase(); 
                }); 
            }; 
     
        for (i in prefix) {
            humpString.push(_toHumb(prefix[i] + '-' + style)); 
        }

        humpString.push(_toHumb(style)); 

        for (i in humpString) 
            if (humpString[i] in htmlStyle) return true; 
     
        return false; 
    }

    /**
     *  QQ登录弹层，引用colorbox插件
     */
    
    function color_box_config(tit, href) {

        return {
            width: "600",
            height: "460",
            iframe: true,
            title: tit,
            opacity: .3,
            href: href
        };
    };

    $.fn.popBox = function() {
        $(this).on('click', function() {
            var title = $(this).data('title');
            var href = $(this).data('href');

            $(this).colorbox(
                color_box_config(title, href )
            );
        })
    }

    $('.pop-box').popBox();
    
    $.fn.placeholder = function(options) {
        var options = $.extend({
            placeholderColor: "#cfcfcf",
            isUseSpan: false,
            onInput: false
        }, options);

        $(this).each(function() {
            var _this = this;
            var supportPlaceholder = "placeholder" in document.createElement("input");
            if (!supportPlaceholder) {
                var defaultValue = $(_this).attr("placeholder");
                var defaultColor = $(_this).css("color");
                if (options.isUseSpan == false) {
                    $(_this).focus(function() {
                        var pattern = new RegExp("^" + defaultValue + "$|^$");
                        pattern.test($(_this).val()) && $(_this).val("").css("color", defaultColor);
                    }).blur(function() {
                        if ($(_this).val() == defaultValue) {
                            $(_this).css("color", defaultColor);
                        } else if ($(_this).val().length == 0) {
                            $(_this).val(defaultValue).css("color", options.placeholderColor);
                        }
                    }).trigger("blur");
                } else {
                    if($(_this).prev('.wrap-placeholder').length == 0){
                        var $imitate = $('<span class="wrap-placeholder" style="position:absolute; overflow:hidden; color:' + options.placeholderColor + "; width:" + $(_this).outerWidth() + "px; height:" + $(_this).outerHeight() + 'px;left:0;top:0;">' + defaultValue + "</span>");
                        $imitate.css({
                            "margin-left": $(_this).css("margin-left"),
                            "margin-top": $(_this).css("margin-top"),
                            "font-size": $(_this).css("font-size"),
                            "font-family": $(_this).css("font-family"),
                            "font-weight": $(_this).css("font-weight"),
                            "padding-left": parseInt($(_this).css("padding-left")) + 2 + "px",
                            "line-height": _this.nodeName.toLowerCase() == "textarea" ? $(_this).css("line-weight") : $(_this).outerHeight() + "px",
                            "padding-top": _this.nodeName.toLowerCase() == "textarea" ? parseInt($(_this).css("padding-top")) + 2 : 0
                        });
                        
                        $imitate.addClass("placeholder");
                        $(_this).before($imitate);
                    }else{
                        var $imitate = $(_this).prev('.wrap-placeholder');
                        $imitate.show();
                    }
                    $imitate.off().on('click', function() {
                        $(_this).trigger("focus");
                    });

                    $(_this).val().length != 0 && $imitate.hide();
                    if (options.onInput) {
                        //绑定oninput/onpropertychange事件

                        var inputChangeEvent = typeof _this.oninput == "object" ? "keyup" : "propertychange";
                        $(_this).bind(inputChangeEvent, function() {
                            $imitate[0].style.display = $(_this).val().length != 0 ? "none" : "inline-block";
                        });
                    } else {
                        $(_this).focus(function() {
                            $(this).prev('span').hide();
                            // $imitate.hide();
                        }).blur(function() {
                            /^$/.test($(_this).val()) && $imitate.show();
                        });

                        var inputChangeEvent = typeof _this.oninput == "object" ? "keyup" : "propertychange";
                        $(_this).bind(inputChangeEvent, function() {
                            $imitate[0].style.display = $(_this).val().length != 0 ? "none" : "inline-block";
                        });

                    }
                   
                }
            }
        });
    }
    
    return {
        valiObj : new Validate(),
        countDown : countDown,
        authcode : authcode
    }


});
